﻿using System;
using System.Reflection;
using System.Linq.Expressions;
using System.Dynamic;
using Microsoft.Scripting;
using Microsoft.Scripting.Actions;

namespace Cjc.Calculation.ExpressionEngine.Excel.Runtime.Binding
{
	public class ExcelConversionBinder : ConvertBinder
	{
		public ExcelBinder Binder { get; private set; }
		public ConversionResultKind ResultKind { get; private set; }

		/// <summary>
		/// Initializes a new instance of the <see cref="ExcelConversionBinder"/> class.
		/// </summary>
		/// <param name="binder">The binder.</param>
		/// <param name="context">The context.</param>
		/// <param name="type">The type.</param>
		/// <param name="resultKind">Kind of the result.</param>
		public ExcelConversionBinder( ExcelBinder binder, Type type, ConversionResultKind resultKind )
			: base( type, resultKind == ConversionResultKind.ExplicitCast || resultKind == ConversionResultKind.ExplicitTry )
		{
			this.Binder = binder;
			this.ResultKind = ResultKind;
		}

		/// <summary>
		/// When overridden in the derived class, performs the binding of the dynamic convert operation if the target dynamic object cannot bind.
		/// </summary>
		/// <param name="target">The target of the dynamic convert operation.</param>
		/// <param name="errorSuggestion">The binding result to use if binding fails, or null.</param>
		/// <returns>
		/// The <see cref="T:Microsoft.Scripting.DynamicMetaObject"/> representing the result of the binding.
		/// </returns>
		public override DynamicMetaObject FallbackConvert( DynamicMetaObject target, DynamicMetaObject errorSuggestion )
		{
			return Binder.ConvertTo( Type, ResultKind, target );
		}
	}
}